package com.lz.common.anno.aop;

import java.util.*;
import java.util.concurrent.*;
import com.google.gson.Gson;
import com.lz.config.dal.entity.MethodLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Aspect
public class AspactCommonsum {

    @Resource
    private Gson gson;
//多线程

    //    多线程map
    public static Map<MethodLog, Integer> map = new ConcurrentHashMap<>();

    public AspactCommonsum() {
    }

    /**
     * 获取
     * @return map
     */
    public static Map<MethodLog, Integer> getMap() {
        return map;
    }

    /**
     * 设置
     * @param map
     */
    public static void setMap(Map<MethodLog, Integer> map) {
        AspactCommonsum.map = map;
    }

    @Pointcut("@annotation(com.lz.common.anno.CommonSum)")
    public void commonSumMethod() {
    }

    @Pointcut("@within(com.lz.common.anno.CommonSum)")
    public void commonSumClass() {
    }

    @Pointcut("commonSumMethod() || commonSumClass()")
    public void commonSum() {
    }

    //前置通知
    @Before("commonSum()")
    public void before(JoinPoint joinPoint) {
        // 同步记录基本信息
        System.out.println("执行了前置通知");
        MethodLog methodLog = new MethodLog();
        methodLog.setMethodName(joinPoint.getSignature().getName());
        methodLog.setCallerMethodName(joinPoint.getSignature().getDeclaringTypeName());
        if (map.containsKey(methodLog)) {
            map.put(methodLog, map.get(methodLog) + 1);
        } else {
            map.put(methodLog, 1);
        }
    }


    public String toString() {
        return "AspactCommonsum{gson = " + gson + ", map = " + map + "}";
    }
}
